package com.byzk.p2p.admin.fuiou.controller;

import java.util.Date;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;


@Controller
@RequestMapping("/fuion")
@Scope("prototype")
public class FuionChangeController extends BaseController{
	@Autowired
	private UserService userService ; 
	@Autowired
	private ChangeService changeService ; 
	@Autowired
	private CallbackService callbackService ;

	@RequestMapping("/change")
	public String change(Integer uid ,Integer cid) throws Exception{
		//出账用户
		User user = userService.getById(uid);
		//进账用户
		ChangeVo vo = changeService.getChange(cid);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(user.getPhone());
		dto.setIn_cust_no(vo.getPhone());
		dto.setContract_no("");
		dto.setRem("");
		double amt = BaseUtil.StringToDoubletoFixed2(vo.getMoney()*100);
		dto.setAmt((int)(amt)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));						
		String backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url,dto);
		System.out.println(backStr);
		Callback callback=new Callback("债权转让",backStr,new Date());
		callbackService.saveOrUpdate(callback);
		String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
		String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
		if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
			changeService.buyChange(uid, cid);
			super.printJSON(new JsonMsg(-1, "操作成功"));
		}else{
			 super.printJSON(new JsonMsg(1, "操作失败"));
		}
		return null ; 		
	}
}
